package com.stu.MyBatis;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class MyBatisTest {
	@Test
	public void mainTest() {
		findUserById();
		findUserByName();
		findAllUser();
		addUser();
		updateUser();
		deleteUser();
	}
	//单条查询
	public void findUserById() {
		SqlSession session = MyBatisUtils.getSession();
		String state = "com.stu.MyBatis.UserMapper.findUserById";
		User user = session.selectOne(state, 1);
		System.out.println(user);
		session.close();
	}
	//模糊查询
	public void findUserByName() {
		SqlSession session = MyBatisUtils.getSession();
		String state = "com.zm.MyBatis.UserMapper.findUserByName";
		List<User> list = session.selectList(state, "张");
		for(User lists:list) {
			System.out.println(lists);
		}
		session.close();
	}
	//查询全部
	public void findAllUser() {
		SqlSession session = MyBatisUtils.getSession();
		String state = "com.stu.MyBatis.UserMapper.findAllUser";
		List<User> list = session.selectList(state);
		for(User lists:list) {
			System.out.println(lists);
		}
		session.close();
	}
	//添加数据
	public void addUser() {
		SqlSession session = MyBatisUtils.getSession();
		String state = "com.stu.MyBatis.UserMapper.addUser";
		User user = new User();
		user.setUsername("李柳");
		user.setPassword("333");
		int rows = session.insert(state, user);
		if(rows>0) {
			System.out.println("添加成功"+rows+"条数据");
		}else {
			System.out.println("添加失败");
		}
		session.commit();
		session.close();
	}
	//更新数据
	public void updateUser() {
		SqlSession session = MyBatisUtils.getSession();
		String state = "com.stu.MyBatis.UserMapper.updateUser";
		User user = new User();
		user.setId(1);
		user.setUsername("李四");
		user.setPassword("321");
		int rows = session.insert(state, user);
		if(rows>0) {
			System.out.println("修改成功"+rows+"条数据");
		}else {
			System.out.println("修改失败");
		}
		session.commit();
		session.close();
	}
	//删除数据
	public void deleteUser(){
		SqlSession session = MyBatisUtils.getSession();
		String state = "com.stu.MyBatis.UserMapper.deleteUser";
		int rows = session.insert(state, 4);
		if(rows>0) {
			System.out.println("删除成功"+rows+"条数据");
		}else {
			System.out.println("删除失败");
		}
		session.commit();
		session.close();
	}
}
